class PubSub {

  public eventMap: Map<string, Set<CallableFunction>>;
  

  constructor() {
    this.eventMap = new Map<string, Set<CallableFunction>>() 
  }

  // 订阅接口
  public on (event: string, fn: Function) {
    // 是否已经存在事件订阅
    const fns = this.eventMap.get(event);

    if (!fns) {
      const sets = new Set<CallableFunction>().add(fn)
      this.eventMap.set(event, sets)
    } else {
      fns.add(fn)
    }
  }

  // 取消订阅
  public off (event: string, fn: Function) {
    // 是否已经存在事件订阅
    const fns = this.eventMap.get(event);

    if (fns) {
      fns.delete(fn);
    }
  }

  // 发布
  public emit(event: string, data: Record<string, any>) {
    this.eventMap.get(event)?.forEach((fn: CallableFunction) => {
      fn(data);
    })
  }
}

export default new PubSub()